package com.sxkiler.demo.rpc.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Properties;

public class NacosTemplate {
    private static Logger logger = LoggerFactory.getLogger(NacosTemplate.class);
    private NamingService namingService;//主要用作服务方面的管理功能
    private static NacosTemplate template = new NacosTemplate();
    //初始化namingService和configService;
    private NacosTemplate(){
        try {
            String serverAddr  = "127.0.0.1:8848";
            String namespace = "nacos_seata";
            Properties properties = new Properties();
            properties.setProperty("serverAddr", serverAddr);
            properties.setProperty("namespace", namespace);
            namingService = NamingFactory.createNamingService(properties);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }


    //注册服务
    public static void registerServer(Instance instance) {
        try {
            template.namingService.registerInstance(instance.getServiceName(),instance);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    //删除服务
    public static void deleteServer(Instance instance) throws Exception{
        template.namingService.deregisterInstance(instance.getServiceName(),instance.getIp(),instance.getPort());
    }

    //随机全部（有可能获取到的不健康）。拿到全部实例后，我们可以按照自己的负载均衡算法进行调用。类似于springcloud的ribbon。
    public static List<Instance> getAllServer(String serverName) throws Exception{
        return template.namingService.getAllInstances(serverName);
    }

    //根据负载均衡算法获取一个健康的实例
    public static Instance getOneHealthyInstance(String serverName) throws Exception{
        return template.namingService.selectOneHealthyInstance(serverName);
    }
}
